<?php // Copyright 2009 J.B.Early - jbnotes.info

class Util {

	public static function asArray($v) {
		if(!$v) return array();
		if(!is_array($v)) return array($v);
		return $v;
	}

	/** Either a, or b (if not a) */
	public static function iif($a,$b) {
		return $a ? $a : $b;
	}

	public static function beginsWith($sub,$str) {
		return $sub === substr($str, 0, strlen($sub));
	}

	public static function endsWith($sub,$str) {
		return $sub === substr($str, strlen($str) - strlen($sub));
	}

	/**
	 * Matches given tokens against the string. Skips whitespace.
	 * Does not check if the token is a whole word.
	 * @param $tok string or string array
	 * @param $str source string; matched tokens will be removed
	 * @return number of tokens matched
	 */
	public static function matchTok($tok,&$str) {
		if (is_array($tok)) {
			$numToks = 0;
			foreach ($tok as $t) {
				if(!($n = self::matchTok($t,$str))) break;
				$numToks += $n;
			}
			return $numToks;
		} else {
			$str = ltrim($str);
			$tl  = strlen($tok);
			if ($tok === substr($str,0,$tl)) {
				$str = substr($str,$tl);
				return 1;
			}
			return 0;
		}
	}

	/**
	 * Removes and returns the next token from str.
	 * The token is either quoted, or terminated by whitespace.
	 * @param $str source
	 * @return string token
	 */
	public static function getTok(&$str) {
		$str = ltrim($str);

		// quoted ?
		@$quo = $str[0];
		if ('\''==$quo || '"'==$quo) {
			$str = substr($str,1);
			$tl  = strcspn($str,$quo);
			$tok = substr($str,0,$tl);
			$str = substr($str,1+$tl);
		} else {
			$tok = strtok($str," \t\n");
			$str = substr($str,strlen($tok));
		}

		return $tok;
	}
}

// eof